# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/22
# Rd
# LiveFat >> predict the MeterScore and stage of liver steatosis in NAFLD populations, based on gradient boosting.
# argument
# item >> inputdata >> a dataframe with values of AST,urea,LDLch,APOA,TBil,FBG and age in NAFLD populations, parameters in columns, samples in rows, rownames corresponding to patient ID.
# item >> print >> a Boolean variable, the default value is "FALSE". If print=TRUE, output a CSV file.
# output >> a dataframe, samples in rows, columns : the MeterScore and Stage of samples
# end

library(gbm)
library(xlsx)
library(dplyr)
library(tibble)


LiveFat <- function(inputdata, print=FALSE){
    load("Model_S0_123.RData")
    load("Model_S1_23.RData")
    load("Model_S2_3.RData")
    L1Score <- round(predict(Model_S0_123, inputdata, n.trees = 400, type = "response"), 2)
    L2Score <- round(predict(Model_S1_23, inputdata, n.trees = 400, type = "response"), 2)
    L3Score <- round(predict(Model_S2_3, inputdata, n.trees = 400, type = "response"), 2)
    lg <- as.numeric(length(L1Score))
    MeterScore <- matrix(nrow = lg, ncol = 1)
    Stage <- matrix(nrow = lg, ncol = 1)
    for (s in 1 : lg) {
        if (L1Score[s] < 0.5) {MeterScore[s] <- L1Score[s] / 2;Stage[s] <- "S0"}else {
            if (L2Score[s] < 0.5) {MeterScore[s] <- 0.25 + L2Score[s] / 2;Stage[s] <- "S1"}else {
                if (L3Score[s] < 0.5) {MeterScore[s] <- 0.5 + L3Score[s] / 2;Stage[s] <- "S2"}else {
                    MeterScore[s] <- 0.5 + L3Score[s] / 2;Stage[s] <- "S3"
                }
            }
        }
    }
    output <- data.frame(cbind(inputdata$id, MeterScore, Stage))
    colnames(output) <- c("id", "MeterScore", "Stage")
    outData <- inputdata %>%
    inner_join(output, by = c("id"))
    return(outData)
}
input <- read.xlsx("input.xlsx", 1, check.names = F) %>%
rownames_to_column("id")
out <- LiveFat(input, print = TRUE)
write.table(out, 'out.txt', sep = '\t', quote = F, row.names = FALSE)


